//
//  QSCustomTabBar.swift
//  TestSwift
//
//  Created by Song on 2018/11/7.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

/// 数据源
protocol QSCustomTabBarDataSource: class {
    /// 除了中间按钮以外还有几个item
    ///
    /// - Parameter tabBar: tabBar
    /// - Returns: item数量
    func qs_numberOfItems(in tabBar: QSCustomTabBar) -> Int
    
    /// 每个item按钮的样式数据
    ///
    /// - Returns: 样式元组
    func qs_tabBar(_ tabBar: QSCustomTabBar, dataForItemAt index: Int) -> (title: String, titleColor: UIColor, selTitleColor: UIColor, img: String, selImg: String)
}

/// 代理
protocol QSCustomTabBarDelegate: class {
    /// 选中哪个item
    func qs_tabBar(tabBar: QSCustomTabBar, didSelectedItemAt index: Int)
    /// 选中中间
    func qs_tabBarDidSelectedCenterItem(tabBar: QSCustomTabBar)
}

class QSCustomTabBar: UITabBar {
    // MARK: - 属性
    private lazy var tabBarView: QSTabBarView = {
        guard let number = self.qs_dataSource?.qs_numberOfItems(in: self) else {
            fatalError("请实现对应的数据源方法")
        }
        
        let tabBarV = QSTabBarView.init(itemOcunt: number)
        tabBarV.qs_delegate = self
        return tabBarV
    }()
    
    /// 代理
    weak var qs_delegate: QSCustomTabBarDelegate?
    /// 数据源
    weak var qs_dataSource: QSCustomTabBarDataSource?
    
    /// 选中中间
    var selectCenter: Bool = false {
        didSet {
            self.tabBarView.qs_selectCenter()
        }
    }
    
    // MARK: - 初始化
    override func layoutSubviews() {
        super.layoutSubviews()

        self.addSubview(self.tabBarView)
        self.tabBarView.frame = self.bounds
        // 把tabBarView带到最前面，覆盖tabBar的内容
        self.bringSubview(toFront: self.tabBarView)
        
        guard let number = self.qs_dataSource?.qs_numberOfItems(in: self) else {
            fatalError("请实现对应的数据源方法")
        }
        
        for index in 0 ..< number {
            guard let itemData = self.qs_dataSource?.qs_tabBar(self, dataForItemAt: index) else {
                fatalError("请实现对应的数据源方法")
            }
            
            // 设置item
            self.setTabBarItem(title: itemData.title, titleColor: itemData.titleColor, selTitleColor: itemData.selTitleColor, img: itemData.img, selImg: itemData.selImg, at: index)
        }
    }
    
    // MARK: - Private Methods
    /// 设置tabBarItem
    ///
    /// - Parameters:
    ///   - title: 文字
    ///   - titleColor: 文字颜色
    ///   - selTitleColor: 选中文字颜色
    ///   - img: 图片
    ///   - selImg: 选中图片
    ///   - index: 下标
    private func setTabBarItem(title: String, titleColor: UIColor = .black, selTitleColor: UIColor = .gray, img: String, selImg: String, at index: Int) {
        self.tabBarView.qs_setTabBarBtn(title: title, titleColor: titleColor, selTitleColor: selTitleColor, img: img, selImg: selImg, at: index)
    }
    
    /// 选中哪个item
    ///
    /// - Parameters:
    ///   - index: 下标
    ///   - isResponseDelegate: 是否响应代理方法，默认响应
    func qs_selectItem(index: Int, isResponseDelegate: Bool = true) {
        self.selectCenter = false
        self.tabBarView.qs_selectItemBtn(index: index, isResponseDelegate: isResponseDelegate)
    }
    
    /// 设置item的badge
    ///
    /// - Parameters:
    ///   - badge: badge的值
    ///   - badge: badge是否隐藏
    ///   - isOnlyRedDot: badge是否只显示一个红点
    ///   - index: item下标
    func qs_itemBadge(_ badge: Int, isHidden: Bool = false, isOnlyRedDot: Bool = true, at index: Int) {
        self.tabBarView.qs_itemBadge(badge, isHidden: isHidden, isOnlyRedDot: isOnlyRedDot, at: index)
    }
    
    // 对中间按钮超出部分的点击事件进行处理
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if self.clipsToBounds || self.isHidden || self.alpha < 0.1 {
            return nil
        }
        
        // 如果事件发生在tabbar里面直接返回
        let result = super.hitTest(point, with: event)
        if let view = result {
            return view
        }
        
        for subView in self.tabBarView.subviews {
            // 把坐标从tabbar的坐标系转为subview的坐标系
            let subPoint = subView.convert(point, from: self)
            let subResult = subView.hitTest(subPoint, with: event)
            // 如果事件发生在subView里就返回
            if let view = subResult {
                return view
            }
        }
        
        return nil
    }
}

extension QSCustomTabBar: QSTabBarViewDelegate {
    func qs_tabBarView(tabBarView: QSTabBarView, didSelectedItemAt index: Int) {
        // 执行代理
        guard let _ = self.qs_delegate?.qs_tabBar(tabBar: self, didSelectedItemAt: index) else { return }
    }
    
    func qs_tabBarViewDidSelectedCenterItem(tabBarView: QSTabBarView) {
        guard let _ = self.qs_delegate?.qs_tabBarDidSelectedCenterItem(tabBar: self) else { return }
    }
}
